package com.my.xinyidaixi.Activity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.MobSDK;
import com.my.xinyidaixi.DataBase.Model.Over_UserModer;
import com.my.xinyidaixi.DataBase.Model.UserModel;
import com.my.xinyidaixi.Globe.MyApplication;
import com.my.xinyidaixi.HttpVolley.Volley_core;
import com.my.xinyidaixi.R;
import com.my.xinyidaixi.Util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by zw on 2017/6/20.
 */
public class login_activity extends Activity
{
    private Context context= MyApplication.getInstance();

    private UserModel moderl=new Over_UserModer();

    private EditText etPhoneNumber,etCode;
    private TextView btnSendMsg,btnSubmitCode;
    private int i = 60;
    private String phoneNum;


    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    //处理验证码消息
    Handler handler=new Handler()
    {
        public void handleMessage(Message msg) {
            if (msg.what == -1) {
                btnSendMsg.setText(i + " s");
            } else if (msg.what == -2) {
                btnSendMsg.setText("重新发送");
                btnSendMsg.setClickable(true);
                i = 60;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("asd", "event=" + event + "  result=" + result + "  ---> result=-1 success , result=0 error");
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        // 提交验证码成功,调用注册接口，之后直接登录
                        //当号码来自短信注册页面时调用登录注册接口
                        //当号码来自绑定页面时调用绑定手机号码接

                        //记下登陆时间
                        preferences=getSharedPreferences("share",MODE_PRIVATE);
                        editor=preferences.edit();
                        editor.putLong("login_time",System.currentTimeMillis());
                        editor.commit();
                        System.out.print("登陆时间为："+System.currentTimeMillis());

                        final Volley_core volley_core=new Volley_core();
                    volley_core.registeruser(etPhoneNumber.getText().toString().trim());
                    volley_core.setVolleycallback(new Volley_core.Registeruser_Callback() {
                        @Override
                        public void flag(boolean flag, final JSONObject json) {
                            if(flag)
                            {
                                new Thread(new Runnable()
                                {
                                    @Override
                                    public void run() {
                                        try {
                                            moderl.addUser(etPhoneNumber.getText().toString().trim(),json.getString("left_money").toString(),json.getString("left_ticket").toString(),json.getString("point").toString());  //存储数据库
                                            volley_core.adress(etPhoneNumber.getText().toString().trim());
                                            volley_core.cleaningorders(etPhoneNumber.getText().toString().trim(),0);
                                            volley_core.clearedorder(etPhoneNumber.getText().toString().trim(),0);
                                            volley_core.getcouponlist(etPhoneNumber.getText().toString().trim());
                                            volley_core.getpointrecord(etPhoneNumber.getText().toString().trim(),0);
                                            volley_core.getchargerecord(etPhoneNumber.getText().toString().trim(),0);
                                        }
                                        catch (JSONException e)
                                        {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                                login_activity.this.setResult(1);
                                login_activity.this.finish();
                                login_activity.this.overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                            }
                            else
                            {
                                ToastUtil.shortToast(login_activity.this,"网络请求失败");
                            }
                        }
                    });
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "验证码已经发送",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {
                    try {
                        Throwable throwable = (Throwable) data;
                        throwable.printStackTrace();
                        JSONObject object = new JSONObject(throwable.getMessage());
                        String des = object.optString("detail");//错误描述
                        int status = object.optInt("status");//错误代码
                        if (status > 0 && !TextUtils.isEmpty(des)) {
                            Log.e("asd", "des: " + des);
                            Toast.makeText(login_activity.this, des, Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (Exception e) {
                        //do something
                    }
                }
            }
        }
    };
    //处理验证码消息
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        initdata();
        yanzheng();
    }

    public void initdata()
    {
        etPhoneNumber = (EditText) findViewById(R.id.etPhoneNumber);
        btnSendMsg = (TextView) findViewById(R.id.btnSendMsg);
        etCode = (EditText) findViewById(R.id.etCode);
        btnSubmitCode = (TextView) findViewById(R.id.login_layout_login);
        btnSubmitCode.setOnClickListener(new button());

        ImageView login_fanhui = (ImageView) findViewById(R.id.login_fanhui);
        login_fanhui.setOnClickListener(new button());
    }



    public class button implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {

            switch (v.getId())
            {
                case R.id.login_fanhui:
                    login_activity.this.finish();
                    login_activity.this.overridePendingTransition(0,R.anim.ani_left_sign_out);
                    break;

                //发送验证码
                case R.id.btnSendMsg:
                    if (TextUtils.isEmpty(phoneNum=etPhoneNumber.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), "手机号码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    SMSSDK.getVerificationCode("86", phoneNum);
                    btnSendMsg.setClickable(false);
                    //开始倒计时
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (; i > 0; i--) {
                                handler.sendEmptyMessage(-1);
                                if (i <= 0) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            handler.sendEmptyMessage(-2);
                        }
                    }).start();
                    break;

                //验证验证码
                case R.id.login_layout_login:

                    String code = etCode.getText().toString().trim();

                    if (TextUtils.isEmpty(phoneNum=etPhoneNumber.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), "手机号码不能为空",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(code)) {
                        Toast.makeText(getApplicationContext(), "验证码不能为空",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    SMSSDK.submitVerificationCode("86",phoneNum, code);
                    break;
            }
        }
    }

    public void yanzheng()
    {
        // 启动短信验证sdk
        MobSDK.init(login_activity.this,"1bd1eb71e3da0","0642aed036ea44e9e53116a7ccdf1e63");
        //initSDK方法是短信SDK的入口，需要传递您从MOB应用管理后台中注册的SMSSDK的应用AppKey和AppSecrete，如果填写错误，后续的操作都将不能进行
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
        btnSendMsg.setOnClickListener(new button());
        btnSubmitCode.setOnClickListener(new button());
        // 启动短信验证sdk
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁回调监听接口
        SMSSDK.unregisterAllEventHandler();
    }

    //当点击的时候实现activity的切换
    @Override
    public void onPause() {
        super.onPause();
        login_activity.this.overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
    }




}
